import * as Cesium from 'cesium';
// const Cesium = window.Cesium
//天地图key
const key = 'd786b5f312e2a5dee39b667a5805263c'

// 初始视图定位在中国
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);

let viewer = null;
function initMap(container) {
    viewer = new Cesium.Viewer(container, {
        // imageryProvider:false,  //关闭默认的imageryProvider
        animation: false,
        baseLayerPicker: false,
        fullscreenButton: false,
        geocoder: false,
        homeButton: false,
        infoBox: false,
        sceneModePicker: false,
        selectionIndicator: false,
        timeline: false,
        navigationHelpButton: false,
        scene3DOnly: true,
        orderIndependentTranslucency: false,
        contextOptions: {
            webgl: {
                alpha: true
            }
        }
    })
    viewer._cesiumWidget._creditContainer.style.display = 'none'
    viewer.scene.fxaa = true
    viewer.scene.globe.enableRoll = true
    viewer.scene.postProcessStages.fxaa.enabled = true
    if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
        // 判断是否支持图像渲染像素化处理
        viewer.resolutionScale = window.devicePixelRatio
    }
    // 移除默认影像
    removeAll()
    // 地形深度测试
    viewer.scene.globe.depthTestAgainstTerrain = true
    // 背景透明
    viewer.scene.globe.baseColor = new Cesium.Color(0.0, 0.0, 0.0, 0)
    // 设置鼠标右键旋转相机视角
    viewer.scene.screenSpaceCameraController.tiltEventTypes = [Cesium.CameraEventType.PINCH, Cesium.CameraEventType.RIGHT_DRAG];
    const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(function (movement) {
        // console.log(movement)
        var pick = viewer.scene.pick(movement.position);
        console.log('*****************', pick);

    },Cesium.ScreenSpaceEventType.LEFT_CLICK);

}
function addGlb(options) {
    let customShader = new Cesium.CustomShader({
        //片元着色器
        fragmentShaderText: `
        void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
            // vec3 positionMC = fsInput.attributes.code;


        }`
    })
    const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        Cesium.Cartesian3.fromDegrees(options.longitude, options.latitude, options.height)
    );
    Cesium.Model.fromGltfAsync({
        id: '111222',
        modelMatrix,
        url: options.url,
        scale: 1,
        minimumPixelSize: 128,
        maximumScale: 20000,
        enablePick: true,
        allowPicking: true,
    }).then((model) => {
        // model.customShader = customShader
        // console.log(model._nodesByName)
        console.log(model)
        const m = viewer.scene.primitives.add(model);
    })
}
function addGlb3(options) {
    const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        Cesium.Cartesian3.fromDegrees(options.longitude, options.latitude, options.height)
    );
    const model = viewer.scene.primitives.add(Cesium.Model.fromGltf({
        id: '111222',
        modelMatrix,
        url: options.url,
        scale: 1,
        minimumPixelSize: 128,
        maximumScale: 20000,
        enablePick: true,
        allowPicking: true,
    }))
    console.log(model)
    // model.readyPromise.then((a, b, c) => {
    //     console.log(a,b,c)
    // })

}
function addGlb2(options) {
    const entity = viewer.entities.add({
        name : options.name,
        description:"<div><p>这是一个飞机！</div>", // 这是模型的描述属性，可以是html标签
        position : options.position,
        orientation : options.orientation,
        model : {
            uri : options.uri,
            minimumPixelSize : 128,
            maximumScale : 20000
        }
    });
}
function addTdtLayer(options) {
    let url = `https://t{s}.tianditu.gov.cn/DataServer?T=${options.type}&x={x}&y={y}&l={z}&tk=${key}`
    const layerProvider = new Cesium.UrlTemplateImageryProvider({
        url: url,
        subdomains: ['0','1','2','3','4','5','6','7'],
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        maximumLevel: 18
    });
    viewer.imageryLayers.addImageryProvider(layerProvider);
}


function addTdtLayer2(options) {
    let url = `https://t{s}.tianditu.gov.cn/${options.type}/wmts?tk=${key}`
    const layerProvider = new Cesium.WebMapTileServiceImageryProvider({
        url: url,
        layer: options.type.slice(0,options.type.length - 2),
        style: 'default',
        format: 'tiles',
        tileMatrixSetID: "w",
        tilingScheme: new Cesium.WebMercatorTilingScheme(),
        subdomains: ['0','1','2','3','4','5','6','7'],
        maximumLevel: 18
    });
    viewer.imageryLayers.addImageryProvider(layerProvider);
}

function changeBaseMap(type) {
    removeAll()
    switch(type) {
        case 0: //影像地图
            addTdtLayer({
                type: 'img_w'
            })
            addTdtLayer({
                type: 'cia_w'
            })
            break
        case 1: //电子地图
            addTdtLayer({
                type: 'vec_w'
            })
            addTdtLayer({
                type: 'cva_w'
            })
            break
        case 2: //地形图
            addTdtLayer({
                type: 'ter_w'
            })
            addTdtLayer({
                type: 'cta_w'
            })
            break
    }
}

function removeAll() {
    viewer.imageryLayers.removeAll();
}

function destroy() {
    viewer.entities.removeAll();
    viewer.imageryLayers.removeAll();
    viewer.destroy();
}

function setView(coords,hpr) {
    viewer.scene.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(coords[0], coords[1], coords[2]),
        orientation: {
            heading: Cesium.Math.toRadians(hpr.heading),
            pitch: Cesium.Math.toRadians(hpr.pitch),
            roll: Cesium.Math.toRadians(hpr.roll),
        }
    });
}


export {
    initMap,
    addTdtLayer,
    changeBaseMap,
    setView,
    addGlb,
    addGlb2,
    addGlb3,
    removeAll,
    destroy
}

